import 'package:app_admin/routes/app_navigator.dart';
import 'package:app_admin/utils/logger.dart';
import 'package:app_admin/utils/data_sp.dart';
import 'package:app_admin/utils/utils.dart';
import 'package:app_admin/widgets/loading_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LoginLogic extends GetxController {
  final phoneCtrl = TextEditingController();
  final pwdCtrl = TextEditingController();
  final obscureText = true.obs;
  final enabled = false.obs;

  _initData() {
    var map = DataSp.getLoginAccount();
    if (map is Map) {
      String? phoneNumber = map["phoneNumber"];
      String? areaCode = map["areaCode"];
      if (phoneNumber != null && phoneNumber.isNotEmpty) {
        phoneCtrl.text = phoneNumber;
      }
    }
  }

  @override
  void onClose() {
    phoneCtrl.dispose();
    pwdCtrl.dispose();
    super.onClose();
  }

  @override
  void onInit() {
    _initData();
    phoneCtrl.addListener(_onChanged);
    pwdCtrl.addListener(_onChanged);
    super.onInit();
  }

  _onChanged() {
    enabled.value =
        phoneCtrl.text.trim().isNotEmpty && pwdCtrl.text.trim().isNotEmpty;
  }

  login() {
    LoadingView.singleton.wrap(asyncFunction: () async {
      var ph = phoneCtrl.text;
      var pwd = IMUtils.emptyStrToNull(pwdCtrl.text);
      var suc = await _login();
      if (suc) {
        AppNavigator.startMain();
      }
    });
  }

  Future<bool> _login() async {
    try {
      // final data = await Apis.login(
      //   areaCode: areaCode.value,
      //   phoneNumber: phoneCtrl.text,
      //   password: IMUtils.emptyStrToNull(pwdCtrl.text),
      // );
      // final account = {
      //   "phoneNumber": phoneCtrl.text
      // };
      // await DataSp.putLoginCertificate(data);
      // await DataSp.putLoginAccount(account);
      // Logger.print('login : ${data.userID}, token: ${data.imToken}');
      // await imLogic.login(data.userID, data.imToken);
      // Logger.print('im login success');
      // pushLogic.login(data.userID);
      // Logger.print('push login success');
      return true;
    } catch (e, s) {
      Logger.print('login e: $e $s');
    }
    return false;
  }

  void openCountryCodePicker() async {
    // String? code = await IMViews.showCountryCodePicker();
    // if (null != code) areaCode.value = code;
  }

  void configService() {}

  void registerNow() {}
}
